'''
Author: 张大鹏
Date: 2020-11-04 08:47:44
LastEditTime: 2020-11-04 09:32:39
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \ai20201027\05.sklearn\02.多因子线性回归分析预测房价.py
'''
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# 解决中文乱码问题
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 数据加载
data = pd.read_csv('usa_housing_price.csv')
# print(data.head())

# 单因子数据可视化
fig = plt.figure(figsize=(10, 10))
# 3行3列图1: 收入与价格散点图
fig1 = plt.subplot(331)
plt.scatter(data.loc[:, 'Avg. Area Income'], data.loc[:, 'Price'])
plt.title('收入与价格散点图')

# 3行3列图2: 房屋年龄与价格散点图
fig2 = plt.subplot(332)
plt.scatter(data.loc[:, 'Avg. Area House Age'], data.loc[:, 'Price'])
plt.title('房屋年龄与价格散点图')

# 3行3列图3: 房间数量与价格散点图
fig3 = plt.subplot(333)
plt.scatter(data.loc[:, 'Avg. Area Number of Rooms'], data.loc[:, 'Price'])
plt.title('房间数量与价格散点图')

# 3行3列图4: 人口数量与价格散点图
fig4 = plt.subplot(334)
plt.scatter(data.loc[:, 'Area Population'], data.loc[:, 'Price'])
plt.title('人口数量与价格散点图')

# 3行3列图5: 房间面积与价格散点图
fig5 = plt.subplot(335)
plt.scatter(data.loc[:, 'size'], data.loc[:, 'Price'])
plt.title('房间面积与价格散点图')

# plt.show()

# 准备单因子模型数据
x = data.loc[:, 'size']  #房屋面积
y = data.loc[:, 'Price']  #价格
x = np.array(x).reshape(-1, 1)  #多行,1列
# print(x, x.shape)

# 建立单因子模型
LR1 = LinearRegression()
# 训练模型
LR1.fit(x, y)

# 计算单因子site对应的的price
y_predict_1 = LR1.predict(x)
# print(y_predict_1)

# 评估模型表现
mean_squared_error_1 = mean_squared_error(y, y_predict_1)
r2_score_1 = r2_score(y, y_predict_1)
# print(mean_squared_error_1, r2_score_1)

# 3行3列图6: 单因子模型预测评估图
fig6 = plt.subplot(336)
plt.scatter(x, y)
plt.plot(x, y_predict_1, 'r')
plt.title('单因子模型预测评估图')

# 多因子模型
x_multi = data.drop(['Price'], axis=1)
# print(x_multi)
# 多因子线性回归结构模型
LR_multi = LinearRegression()
# 训练模型
LR_multi.fit(x_multi, y)
# 模型预测
y_predict_multi = LR_multi.predict(x_multi)
# print(y_predict_multi)

# 评估模型表现
mean_squared_error_multi = mean_squared_error(y, y_predict_multi)
r2_score_multi = r2_score(y, y_predict_multi)
# print(mean_squared_error_multi, r2_score_multi)

# 3行3列图7: 多因子模型预测评估图
fig7 = plt.subplot(337)
plt.scatter(y, y_predict_multi)
plt.title('多因子模型预测评估图')

# 用测试数据预测房价
x_test = [86295, 4.372543, 8.011898, 47560.78, 231.0471]
# print(type(x_test))
x_test = np.array(x_test).reshape(1, -1)  # 1行多列
# print(x_test)
y_test_predict = LR_multi.predict(x_test)
print(y_test_predict)
plt.show()